from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from goods.models import SKU
from rest_framework.response import Response
from . import serializers
from decimal import Decimal


class OrderSettlementView(APIView):
    """提交购物车数据，进行展示"""
    permission_classes = [IsAuthenticated]      # 必须是登录用户

    def get(self, request):
        """根据用户的user_id获取redis中存储勾选的sku_id，所有我们需要自己实现"""
        user = request.user
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        # 获取勾选用户
        redis_cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
        print(redis_cart_selected, 'hahahaha')
        # skus_id = redis_cart.keys()   # bytes类型
        # 使用序列化器返回相应数据
        skus = []
        for sku_id in redis_cart_selected:
            count = redis_cart[sku_id]
            sku_id = int(sku_id)
            sku = SKU.objects.get(id=sku_id)
            count = int(count)
            sku.count = count
            skus.append(sku)

        serializer = serializers.CartSKUSerializer(instance=skus, many=True)
        freight = Decimal('10.00')
        return Response({'freight': freight, 'skus': serializer.data})


class SaveOrderView(CreateAPIView):
    """保存订单"""
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.SaveOrderSerializer
